﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace JBBRXG11_V0._9._50._02_FixSetupFileLocations
{
    public partial class Form1 : Form
    {
        #region Utilities
        public Form1()
        {
            InitializeComponent();
        }

        void print(string msg)
        {
            tb.Text += msg;
        }

        void println()
        {
            tb.Text += "\r\n";
        }

        void println(string msg)
        {
            print(msg);
            println();
        }
        #endregion

        List<string> lines, newlines;
        string here, setupdir;
        string tag = "<<@PUTPROJECTFOLDERHERE@>>";

        void FindPaths()
        {
            here = Path.GetFullPath(@".\..\..\..\..\");
            setupdir = here + @"\JBBRXG11-V0.9.50.02-Setup\Setup";
            println("Looking at => " + setupdir);
            foreach (string file in Directory.GetFiles(setupdir)) println(" ... " + file);
        }

        void ReadSetupFile(string filename)
        {
            println("Trying to open >>" + setupdir + filename);
            StreamReader sr = new StreamReader(setupdir + filename);
            lines = new List<string>();
            while (!sr.EndOfStream) lines.Add(sr.ReadLine());
            sr.Close();
        }

        void MakeNewFile(string oldtext, string newtext)
        {
            newlines = new List<string>();
            foreach (string line in lines)
            {
                int at = line.ToUpper().IndexOf(oldtext.ToUpper());
                if (at < 0)
                    newlines.Add(line);
                else
                {
                    string newline = line.Substring(0, at) + newtext + line.Substring(at + oldtext.Length);
                    println();
                    println(line);
                    println(newline);
                    newlines.Add(newline);
                }
            }
        }

        void WriteNewFile(string filename)
        {
            StreamWriter sw = new StreamWriter(setupdir + filename);
            foreach (string newline in newlines) sw.WriteLine(newline);
            sw.Close();
        }

        private void ToTaggedButton_Click(object sender, EventArgs e)
        {
            FindPaths();
            ReadSetupFile(@"\Setup.isl");
            MakeNewFile(here, tag);
            WriteNewFile(@"\Setup.isl-tagged");
        }

        private void ToNewLocationButton_Click(object sender, EventArgs e)
        {
            FindPaths();
            ReadSetupFile(@"\Setup.isl-tagged");
            MakeNewFile(tag, here);
            WriteNewFile(@"\Setup.isl");
        }
    }
}
